<template>
  <el-dialog
    customClass="customWidth"
    title="新增"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form :model="dataForm" inline ref="dataForm" label-width="0px" style="width:100%">
      <el-form-item prop="pfId">
        <el-select
          :disabled="true"
          v-model="dataForm.pfId"
          placeholder="请选择销售平台"
          style="width:100%"
        >
          <el-option v-for="item in pfs" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="storId">
        <el-select
          :disabled="true"
          v-model="dataForm.storId"
          placeholder="请选择店铺"
          style="width:100%"
        >
          <el-option v-for="item in stores" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select :disabled="true" v-model="dataForm.groupId"  placeholder="请选择分组">
          <el-option v-for="item in groups" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dfHotel.province" clearable @change="proChange" placeholder="请选择省份">
          <el-option
            v-for="item in provinces"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dfHotel.city" clearable @change="cityChange" placeholder="请选择城市">
          <el-option
            v-for="item in citys"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dfHotel.county" clearable placeholder="请选择区域">
          <el-option
            v-for="item in countys"
            :key="item.cityCode"
            :label="item.cityNameZh"
            :value="item.cityCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dfHotel.brand" clearable placeholder="请选择品牌">
          <el-option v-for="item in brands" :key="item.id" :label="item.bname" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input v-model="dataForm.hotelName" clearable placeholder="酒店名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="primary" @click="select" :disabled="dataListSelections.length <= 0">添加</el-button>
      </el-form-item>
      <el-form-item :inline="true">
            <el-upload
              class="upload-demo"
              action=""
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :limit="limitUpload"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :auto-upload="false"
            >
              <el-button type="primary">点击导入酒店</el-button>
            </el-upload>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="hotelName" header-align="center" align="center" label="酒店名称"></el-table-column>
      <el-table-column prop="address" header-align="center" align="center" label="酒店地址"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[5, 10]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit">提交</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { treeDataTranslate } from "@/utils"
export default {
  data() {
    return {
      limitUpload: 1,
      visible: false,
      active: 0,
      dfHotel: {
        province: null,
        city: null,
        county: null,
        brand: null
      },
      pfs: [],
      stores: [],
      groups: [],
      tier: 1,
      parentId: -1,
      provinces: [],
      citys: [],
      countys: [],
      brands: [],
      dataForm: {
        dtId: null,
        pfId: null,
        storId: null,
        groupId: null,
        groupName : null,
        hotelName: null,
        hotelIds: []
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 5,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: []
    }
  },
  methods: {
    //上传文件时处理方法
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      this.importfxx(this.fileTemp);

    },
    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            arr.push(v["酒店id"]);
          });
          console.info(arr);
          _this.dataForm.hotelIds = arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    // 获取区域查询条件
    getQuryCitys() {
      this.$http({
        url: this.$http.adornUrl('/op/group/citys'),
        method: 'post',
        params: this.$http.adornParams({
          tier: this.tier,
          parentId: this.parentId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          switch (this.tier) {
            case 1:
              this.provinces = data.list
              break
            case 2:
              this.citys = data.list
              break
            case 3:
              this.countys = data.list
              break
          }
        }
      })
    },
    // 查询品牌
    getBrands() {
      this.$http({
        url: this.$http.adornUrl('/op/group/brand'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.brands = data.list
        }
      })
    },
    // 选择省份
    proChange(value) {
      this.parentId = value
      this.tier = 2
      this.getQuryCitys()
    },
    // 选择城市
    cityChange(value) {
      this.parentId = value
      this.tier = 3
      this.getQuryCitys()
    },
    query(){
      this.pageIndex = 1
      this.queryByName()
    },
    // 获取指定的酒店（按酒店名称）
    queryByName() {
      this.dataListSelections = []
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/op/htlgroup/hotels'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'dtId': this.dataForm.dtId,
          'pfId': this.dataForm.pfId,
          'storId': this.dataForm.storId,
          // 'province': this.dfHotel.province,
          'city': this.dfHotel.city,
          'county': this.dfHotel.county,
          'brand': this.dfHotel.brand,
          'name': this.dataForm.hotelName,
          'groupId':this.dataForm.groupId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.queryByName()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.queryByName()
    },
    select() {
      if (this.dataListSelections.length <= 0) {
        return
      }
      let ids = this.dataListSelections.map(item => {
        return item.hotelId
      })
      // 把选择的酒店添加到酒店列表
      this.dataForm.hotelIds = this.dataForm.hotelIds.concat(ids)
      // 去重
      this.dataForm.hotelIds = this.dataForm.hotelIds.filter((item, index) => {
        return this.dataForm.hotelIds.indexOf(item) === index
      });
      this.dataListSelections = []
    },
    init(dtId, pfId, pfs, storId, stores, groupId,groups) {
      this.dataForm.dtId = dtId
      this.pfs = pfs
      this.stores = stores
      this.dataForm.pfId = pfId
      this.dataForm.storId = storId
      this.dataForm.groupId = groupId
      this.groups = groups
      this.getQuryCitys()
      this.getBrands()
      this.visible = true
      this.active = 0
    },
    // 表单提交
    dataFormSubmit() {
      this.select()
      if (this.dataForm.hotelIds === null || this.dataForm.hotelIds.length <= 0) {
        this.$message({
          message: '请选择酒店',
          type: 'success',
          duration: 1000,
        })
        return
      }
      this.$http({
        url: this.$http.adornUrl("/op/htlgroup/save"),
        method: 'post',
        data: this.$http.adornData({
          'dtId': this.dataForm.dtId,
          'pf' : this.dataForm.pfId,
          'storId': this.dataForm.storId,
          'id': this.dataForm.groupId,
          'groupName' : this.dataForm.groupName,
          'hotelIds': this.dataForm.hotelIds
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.dataListSelections = []
            }
          })
          this.$emit('refreshDataList')
        } else {
          this.$message.error(data.msg)
        }
      })
    }
  }
}
</script>
<style>
.customWidth {
  width: 80%;
}
</style>
